package com.retain.system.service.impl;

import com.retain.system.dto.UserDTO;
import com.retain.system.exception.BusinessException;
import com.retain.system.mappers.UserMapper;
import com.retain.system.service.ResourceService;
import com.retain.system.service.RoleService;
import com.retain.system.service.UserService;
import com.retain.system.vo.ResourceVO;
import com.retain.system.vo.RoleVO;
import com.retain.system.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: LiuWei
 * @date: Create in 11:29 2018/10/15
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;


    @Override
    public UserDTO add(UserDTO user) {
        if (userMapper.insert(user) != 1) {
            throw new BusinessException("user insert error");
        }
        return user;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(UserDTO user) {
        if (userMapper.deleteByPrimaryKey(user.getId()) != 1) {
            throw new BusinessException("delete error");
        }
        roleService.deleteRUByUserId(user.getId());
        return true;
    }

    @Override
    public UserDTO update(UserDTO user) {
        if (userMapper.updateByPrimaryKeySelective(user) != 1) {
            throw new BusinessException("update error");
        }
        return user;
    }

    @Override
    public UserVO findUserByAccount(String account) {

        Example example = new Example(UserDTO.class);
        example.createCriteria().andEqualTo("account", account);
        UserDTO userDTO = userMapper.selectOneByExample(example);
        if (userDTO == null) {
            return null;
        }


        //找到roles
        List<RoleVO> roleVOS = roleService.selectRolesByUserId(userDTO.getId());
        //找到所有Resource

        List<Long> roleIds = new ArrayList<>(roleVOS.size());
        roleVOS.forEach(roleVO -> roleIds.add(roleVO.getId()));

        List<ResourceVO> resourceVOS = resourceService.selectResourceByUserId(roleIds);
        return UserVO.buildUserVO(userDTO, roleVOS, resourceVOS);
    }


}
